package com.xuecheng.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.mapper.XcUserRoleMapper;
import com.xuecheng.ucenter.model.dto.RegistParamsDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.model.po.XcUserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
public class RegistController {

    @Autowired
    XcUserMapper userMapper;
    @Autowired
    CheckCodeClient checkCodeClient;
    @Autowired
    XcUserRoleMapper userRoleMapper;

    @Transactional
    @PostMapping("/register")
    public void register(@RequestBody RegistParamsDto registParamsDto) {
//        XcUser xcUser = userMapper.selectById(id);
        Boolean verify = checkCodeClient.verify(registParamsDto.getCheckcodekey(), registParamsDto.getCheckcode());
        if(!verify || verify==null){
            XueChengPlusException.cast("验证码输入错误");
//            throw new RuntimeException("验证码输入错误");
        }
        if (!registParamsDto.getPassword().equals(registParamsDto.getConfirmpwd())) {
            XueChengPlusException.cast("密码不一致");
//            throw new RuntimeException("密码不一致");
        }
        LambdaQueryWrapper<XcUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(XcUser::getUsername,registParamsDto.getUsername());
        wrapper.eq(XcUser::getPassword,registParamsDto.getPassword());
        List<XcUser> xcUsers = userMapper.selectList(wrapper);
        if (xcUsers!=null && xcUsers.size()>0){
            XueChengPlusException.cast("用户存在");
//            throw new RuntimeException("用户存在");
        }
        XcUser xcUser = new XcUser();
        BeanUtils.copyProperties(registParamsDto,xcUser);
        xcUser.setCreateTime(LocalDateTime.now());
        xcUser.setStatus("1");
        xcUser.setName(xcUser.getNickname());
        xcUser.setUtype("101001");
        int insert = userMapper.insert(xcUser);
        if (insert<=0){
            XueChengPlusException.cast("插入失败");
        }
        XcUserRole userRole = new XcUserRole();
        userRole.setRoleId("17");
        userRole.setUserId(xcUser.getId());
        userRole.setCreateTime(LocalDateTime.now());
        userRole.setCreator("学生");
        userRoleMapper.insert(userRole);
    }
}
